"use strict";

import {Utils} from "./utils";

export class Packet {
    static key = "b8ca9aa66def05ff3f24919274bb4a66";
    static pack(operator, sequence, header, body) {
        header = Utils.encrypt(header, Packet.key, Packet.key);
        body = Utils.encrypt(body, Packet.key, Packet.key);

        let headerLength = header.length;
        let bodyLength = body.length;

        let buf = new ArrayBuffer(20 + headerLength + bodyLength);
        let dataView = new DataView(buf);
        sequence= sequence.toString();
        dataView.setUint32(0, operator);
        dataView.setUint32(4, parseInt(sequence.slice(0, 6)));
        dataView.setUint32(8, parseInt(sequence.slice(6)));
        dataView.setUint32(12, headerLength);
        dataView.setUint32(16, bodyLength);

        let bufView = new Uint8Array(buf);
        for (let i = 0; i < headerLength; i++) {
            bufView[20 + i] = header.charCodeAt(i);
        }

        for (let i = 0; i < bodyLength; i++) {
            bufView[20 + headerLength + i] = body.charCodeAt(i);
        }

        return buf;
    }

    static unPack(data) {
        let dataView = new DataView(data);

        Packet.operator = dataView.getUint32(0, false);
        Packet.sequence = parseInt(dataView.getUint32(4, false).toString() + dataView.getUint32(8, false).toString(), 10);
        Packet.headerLength = dataView.getUint32(12, false);
        Packet.bodyLength = dataView.getUint32(16, false);

        let header = Utils.ab2str(dataView.buffer.slice(20, 20 + Packet.headerLength));
        let body = Utils.ab2str(dataView.buffer.slice(20 + Packet.headerLength));

        Packet.header = Utils.decrypt(header, Packet.key, Packet.key);
        Packet.body = Utils.decrypt(body, Packet.key, Packet.key);

        return Packet;
    }
}
